<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="套餐名" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐价格" prop="packagePrice">
        <el-input
          v-model="queryParams.packagePrice"
          placeholder="请输入套餐价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="packageStatus">
        <el-select v-model="queryParams.packageStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.package_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:package:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:package:edit']"
        >详情和修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:package:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:package:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐id" align="center" prop="packageId" />
      <el-table-column label="套餐名" align="center" prop="packageName" />
      <el-table-column label="套餐价格" align="center" prop="packagePrice" />
      <el-table-column label="状态" align="center" prop="packageStatus">
        <!-- <template slot-scope="scope">
          <dict-tag :options="dict.type.package_status" :value="scope.row.packageStatus" />
        </template> -->
        <template slot-scope="scope">
    <dict-tag :options="dict.type.package_status" :value="scope.row.packageStatus"  style="display: none;"/>
    <el-tag v-if="scope.row.packageStatus === '0'" type="info">下架</el-tag>
    <el-tag v-else-if="scope.row.packageStatus === '1'">上架</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:package:edit']"
          >查看详情/修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:package:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务套餐管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名" />
        </el-form-item>
        <el-form-item label="套餐价格" prop="packagePrice">
          <el-input v-model="form.packagePrice" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-form-item label="状态" prop="packageStatus">
          <el-select v-model="form.packageStatus" placeholder="请选择状态">
            <el-option
              
              v-for="dict in dict.type.package_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-divider content-position="center">套餐的服务内容信息</el-divider>

        <el-table
          :data="tbServicePackageAssociationList"
          :row-class-name="rowTbServicePackageAssociationIndex"
          @selection-change="handleTbServicePackageAssociationSelectionChange"
          ref="tbServicePackageAssociation"
        ></el-table>
        <template>
          <el-transfer
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入服务内容搜索"
            v-model="selectedKeys"
            :data="serviceContents"
            :titles="['全部服务', '已选服务']"
          ></el-transfer>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPackage,
  getPackage,
  delPackage,
  addPackage,
  updatePackage
} from "@/api/system/package";
import { listServiceContent } from "@/api/system/serviceContent";

export default {
  name: "Package",
  dicts: ["package_status"],
  data() {
    return {
      // 穿梭框
      filterMethod(query, item) {
        return item.str.indexOf(query) > -1;
      },
      serviceContents: [], // 存储服务内容列表
      selectedKeys: [], // 存储已选服务的ID
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbServicePackageAssociation: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务套餐管理表格数据
      packageList: [],
      // 服务-套餐关联表格数据
      tbServicePackageAssociationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: null,
        packagePrice: null,
        packageStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询服务套餐管理列表 */
    getList() {
      this.loading = true;
      listPackage(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        packageId: null,
        packageName: null,
        packagePrice: null,
        packageStatus: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.tbServicePackageAssociationList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      (this.selectedKeys = []), this.reset();
      this.open = true;
      this.title = "添加服务套餐管理";
      listServiceContent().then(resp => {
        this.serviceContents = resp.rows.map(q => ({
          label: q.serviceContent, // 服务内容
          key: q.serviceId, // 服务ID
          str: q.serviceContent // 服务内容字符串
        }));
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const packageId = row.packageId || this.ids;
      getPackage(packageId).then(response => {
        this.form = response.data;
        this.tbServicePackageAssociationList =
          response.data.tbServicePackageAssociationList;
        this.selectedKeys = this.tbServicePackageAssociationList.map(
          item => item.serviceId
        ); // 设置已选服务的ID
        this.open = true;
        this.title = "修改服务套餐管理";

        listServiceContent().then(resp => {
          this.serviceContents = resp.rows.map(q => ({
            label: q.serviceContent, // 服务内容
            key: q.serviceId, // 服务ID
            str: q.serviceContent // 服务内容字符串
          }));
        });
      });
    },

    /** 提交按钮 */
    submitForm() {
      console.log("Selected Keys:", this.selectedKeys);
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构建提交的数据，确保包含所有必要的信息
          this.form.tbServicePackageAssociationList = this.selectedKeys.map(
            key => {
              const service = this.serviceContents.find(
                service => service.key === key
              );
              return {
                serviceId: key,
                serviceContent: service ? service.label : "Unknown Service", // 假设后端需要服务内容
                delFlag: "0"
              };
            }
          );

          console.log("Form Data before submit:", this.form); // 输出查看完整的表单数据

          if (this.form.packageId != null) {
            // 更新现有套餐
            updatePackage(this.form)
           
              .then(response => {
                console.log("Update Package Response:", response);
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch(error => {
                console.error("Update Package Error:", error);
                this.$modal.msgError("修改失败: " + error.message);
              });
          } else {
            // 添加新套餐
            addPackage(this.form)
              .then(response => {
                console.log("Add Package Response:", response);
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(error => {
                console.error("Add Package Error:", error);
                this.$modal.msgError("新增失败: " + error.message);
              });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$modal
        .confirm('是否确认删除服务套餐管理编号为"' + packageIds + '"的数据项？')
        .then(function() {
          return delPackage(packageIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 服务-套餐关联序号 */
    rowTbServicePackageAssociationIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 服务-套餐关联添加按钮操作 */
    handleAddTbServicePackageAssociation() {
      let obj = {};
      obj.serviceId = "";
      this.tbServicePackageAssociationList.push(obj);
    },
    /** 服务-套餐关联删除按钮操作 */
    handleDeleteTbServicePackageAssociation() {
      if (this.checkedTbServicePackageAssociation.length == 0) {
        this.$modal.msgError("请先选择要删除的服务-套餐关联数据");
      } else {
        const tbServicePackageAssociationList = this
          .tbServicePackageAssociationList;
        const checkedTbServicePackageAssociation = this
          .checkedTbServicePackageAssociation;
        this.tbServicePackageAssociationList = tbServicePackageAssociationList.filter(
          function(item) {
            return checkedTbServicePackageAssociation.indexOf(item.index) == -1;
          }
        );
      }
    },
    /** 复选框选中数据 */
    handleTbServicePackageAssociationSelectionChange(selection) {
      this.checkedTbServicePackageAssociation = selection.map(
        item => item.index
      );
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/package/export",
        {
          ...this.queryParams
        },
        `package_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
